<template>
  <div>
    <div class="header-box">
      <span>列表更多操作将展示所配置导出项，可根据所配置数据模板进行导出数据</span>
      <PlainCreateBtn @click="addDataForm">添加导出表</PlainCreateBtn>
    </div>
    <template v-if="dataForms && dataForms.length">
      <div v-for="formItem in dataForms" :key="formItem.reportKey" class="form-item">
        <div class="form-header">
          <span class="red-text">*</span><span class="form-name">导出表名称</span>
          <el-input v-model="formItem.reportName" type="text" maxlength="50" placeholder="请输入" size="small" class="width240 input"/>
          <div v-if="showMainSubform(formItem)" class="flex-center ml12">
            <span class="red-text">*</span><span class="form-name">主子表单</span>
            <selectWithoutHttp v-model="formItem.mainFormKey" :list-data="formItem.listData" filterable class="select width240" label-name="name" key-name="key" placeholder="请选择" />
          </div>
          <div class="btn-wrap">
            <img :src="copyIcon" class="icon" alt="复制" @click.stop="copyForm(formItem)">
            <img :src="deleteIcon" class="icon" alt="删除" @click.stop="delForm(formItem.reportKey)">
          </div>
        </div>
        <ExportGraggable v-model="formItem.fields" @getCurSelectedNum="getCurSelectedNum" @setListData="setListData(formItem.reportKey)"/>
      </div>
    </template>
    <EmptyPlaceholder v-else :empty-text-top="0" text="暂无数据表" />
  </div>
</template>

<script>
import SectionTitle from '@/components/Title';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ExportGraggable from './module/exportGraggable';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import { forEachFormOptions } from '@/utils/formMakeUtils';
import { generateUUID } from '@/utils/tools';
import { dataFieldTargets } from './settingTargets';
import { showModal } from '@/utils/message';
import copyIcon from '@/assets/auditProcess/copy_form.png';
import deleteIcon from '@/assets/auditProcess/delete_form.png';
export default {
  name: 'DataSetting',
  components: {
    SectionTitle,
    EmptyPlaceholder,
    ExportGraggable,
    selectWithoutHttp
  },
  props: {
    formList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      copyIcon,
      deleteIcon,
      dataStatus: false,
      dataForms: [],
      listFields: []
    };
  },
  watch: {
    dataForms: {
      handler() {
        this.statusCheck();
      },
      deep: true
    }
  },
  created() {
    this.statusCheck();
  },
  methods: {
    // 初始化字段列表
    initList(formList) {
      this.listFields = [];
      forEachFormOptions(formList, item => {
        if (dataFieldTargets.includes(item.type)) { // 统计字段单独处理
          const statisticsType = ['linkForm'];
          if (statisticsType.includes(item.type)) {
            const { statistics } = item.options;
            if (statistics && statistics.length) {
              statistics.forEach(key => {
                const findIndex = item.subform.findIndex(subItem => subItem.key === key);
                findIndex !== -1 && this.listFields.push({ isCheck: false, ...item.subform[findIndex], isStatistics: true });
              });
            }
          } else {
            this.listFields.push({ isCheck: false, ...item, isStatistics: false });
          }
        }
      });
      this.listFields = this.listFields.filter(el => { // 隐藏加密字段
        if (el.options) {
          return !el.options.isSecret;
        }
        return true;
      });
      this.initDataForm();
    },
    // 回填数据表
    initDataForm() {
      if (!this.dataForms) return;
      const initFields = this.initFields() || [];
      this.dataForms.map(i => {
        const fields = _.cloneDeep(initFields);
        const listData = [];
        i.fields.map(j => {
          const index = fields.findIndex(k => k.key === j.key);
          if (index !== -1) {
            if (fields[index].isSubTable && j.isCheck) {
              const subformItem = this.formList.find(el => fields[index].linkFormKey === el.key);
              if (!listData.find(j => subformItem.key === j.key)) {
                listData.push({
                  key: subformItem.key,
                  name: subformItem.name
                });
              }
            }
            // 原有字段部分属性不可更新
            const { isCheck, name } = j;
            fields[index] = Object.assign(fields[index], { isCheck, name });
          }
        });
        this.$set(i, 'fields', fields);
        this.$set(i, 'listData', listData);
      });
      this.resetMainFormKey();
    },
    // 去重已选中后被删除的主子表单
    resetMainFormKey() {
      this.dataForms.forEach(item => {
        if (item.mainFormKey) {
          if (Array.isArray(item.listData) && item.listData.length) {
            const allSubformKeys = item.listData.map(subform => subform.key);
            if (!allSubformKeys.includes(item.mainFormKey)) item.mainFormKey = '';
          } else {
            item.mainFormKey = '';
          }
        }
      });
    },
    showMainSubform(data) {
      if (data.listData) {
        if (data.listData.length === 1) {
          data.mainFormKey = data.listData[0].key;
          return false;
        }
        if (data.listData.length > 1) {
          this.resetMainFormKey();
          return true;
        }
      }
      return false;
    },
    statusCheck() {
      this.dataStatus = this.validate();
      this.$emit('statusCheck');
      this.$emit('updateExportDot', this.dataStatus);
    },
    validate() {
      if (!this.dataForms) return false;
      let valid = false;
      this.dataForms.find(i => {
        if (!i.reportName || (!i.mainFormKey && i.listData && i.listData.length > 1)) {
          valid = true;
        }
        // 是否勾选同步字段
        const selectNum = i.fields.reduce((pre, curr) => pre + (curr['isCheck'] ? 1 : 0), 0);
        if (selectNum < 1) {
          valid = true;
        }
      });
      return valid;
    },
    // 校验表单
    validateForm() {
      return new Promise((resolve, reject) => {
        this.dataForms.find(i => {
          if (!i.reportName || (!i.mainFormKey && i.listData && i.listData.length > 1)) {
            reject('请检查高级设置-列表设置-导出字段配置是否填写完整');
            return;
          }
          if (this.dataForms.filter(j => j.reportKey !== i.reportKey).find(k => k.reportName === i.reportName)) {
            reject(`【${i.reportName}数据表】名称与其他导出表名称重复，请调整后再保存`);
            return;
          }
          // 是否勾选同步字段
          const selectNum = i.fields.reduce((pre, curr) => pre + (curr['isCheck'] ? 1 : 0), 0);
          if (selectNum < 1) {
            reject('请勾选高级设置-列表设置-导出字段配置所需字段');
            return;
          }
        });
        resolve(true);
      });
    },
    setData(dataForms = []) {
      this.dataForms = dataForms || [];
    },
    getData() {
      const data = JSON.parse(JSON.stringify(this.dataForms));
      // 当只勾选一个子表单的字段，默认主子表单为当前勾选
      data.map(i => {
        if (i.listData && i.listData.length === 1) {
          i.mainFormKey = i.listData[0].key;
        }
        i.fields.map((j, index) => {
          const { name, realName, key, linkFormKey, isCheck, isStatistics, type } = j;
          i.fields[index] = { name, realName, key, linkFormKey, isCheck, isStatistics, type };
          if (j.type === 'date' && j.options) {
            i.fields[index].format = j.options.format;
          } else if (j.type === 'input' && j.options && j.options.dataType === 'number') {
            i.fields[index].precision = j.options.precision;
            i.fields[index].isShowPercentage = j.options.isShowPercentage;
          }
        });
      });
      return data;
    },
    addDataForm() {
      const fields = this.initFields();
      this.dataForms.push({
        reportKey: generateUUID(),
        reportName: '',
        mainFormKey: '',
        fields,
        listData: []
      });
      this.statusCheck();
    },
    copyForm(item) {
      const copyItem = JSON.parse(JSON.stringify(item));
      delete copyItem.reportKey;
      copyItem.reportName = copyItem.reportName ? copyItem.reportName + '-副本' : '';
      this.dataForms.push({
        reportKey: generateUUID(),
        ...copyItem
      });
    },
    delForm(reportKey) {
      showModal('请确认是否删除').then(_ => {
        const findIndex = this.dataForms.findIndex(el => el.reportKey === reportKey);
        this.dataForms.splice(findIndex, 1);
      });
    },
    getCurSelectedNum(length) {
      this.dataStatus = length < 1;
      this.$emit('statusCheck');
      this.$nextTick(() => {
        this.$emit('updateExportDot', this.dataStatus);
      });
    },
    initFields() {
      const fields = JSON.parse(JSON.stringify(this.listFields));
      fields.map(el => {
        el.realName = el.name;
        if (el.isSubTable || el.linkFormKey) {
          const subformItem = this.formList.find(j => el.linkFormKey === j.key);
          if (subformItem) {
            el.realName = subformItem.name + '.' + el.name;
          }
        }
      });
      return fields;
    },
    // 获取主子表单列表
    setListData(reportKey) {
      const index = this.dataForms.findIndex(el => el.reportKey === reportKey);
      const listData = [];
      this.dataForms[index].fields.map(el => {
        if (el.isSubTable && el.isCheck) {
          const subformItem = this.formList.find(j => el.linkFormKey === j.key);
          if (!listData.find(j => subformItem.key === j.key)) {
            listData.push({
              key: subformItem.key,
              name: subformItem.name
            });
          }
        }
      });
      this.$set(this.dataForms[index], 'listData', listData);
    }
  }
};
</script>

<style scoped lang="scss">
.header-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  > span {
    color: #999;
    font-size: 14px;
  }
}
.title-tip {
  flex: 1;
  font-size: 14px;
  color: #999;
  font-weight: normal;
  margin-left: 6px;
}
.fields-checkbox {
  margin-left: 6px;
  & ::v-deep {
    .el-checkbox__label {
      font-size: 12px;
      padding-left: 4px;
    }
    .el-checkbox {
      color: #333;
    }
  }
}
.form-item{
  margin: 16px 0 20px;
  .form-name {
    font-size: 14px;
    color: #666666;
    margin-right: 12px;
  }
}
.form-header {
  display: flex;
  align-items: center;
  background: #F8F8F9;
  padding: 12px 16px;

  .red-text {
    color: red;
    margin-right: 2px;
  }

  .input, .select {
    margin-right: 12px;
  }

  img {
    width: 14px;
    height: 14px;
    margin-left: 4px;
  }

  .btn-wrap {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .icon {
    margin-left: 12px;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background: #fff;
  }

  .width120 {
    width: 120px;

    & ::v-deep {
      .el-input__inner {
        width: 120px !important;
      }
    }
  }

  .width240 {
    width: 240px;

    & ::v-deep {
      .el-input__inner {
        width: 240px !important;
      }
    }
  }
}
</style>
